<?php
/**
* @name Maiji
* @author pd87@qq.com
* @copyright m-j.cc
* @version v1.0
*/
class Loader
{
    public static function baseLoad()
    {
		if(C('basic.cache') === false){
			require_once(APP_INI_PATH."libs/action.php");
			require_once(APP_INI_PATH."libs/Db/Connection.php");
			require_once(APP_INI_PATH."libs/model.php");
		}
    }
    public static function searchFile($filename,$path)
    {
		if(!is_dir($path)){
			return false;
		}
		if(!is_file($path.$filename)){
			return false;
		}
        $filePath = false;
        $list = scandir($path);
        foreach($list as $file){
            $realPath = $path.DIRECTORY_SEPARATOR.$file;
			
            if(is_dir($realPath) && $file!='.' && $file!='..'){
                $res = Loader::searchFile($filename,$realPath);
                if($res){
                    return $res;
                }
            }elseif($file!='.' && $file!='..'){
                if($file == $filename){
                    $filePath = $realPath;
                    break;
                }
            }
        }
        return $filePath;
    }
    public static function autoload($class){
		if(strpos($class,'Smarty_') === false){
			$class .= ".php";
			$_ls = explode('\\',$class);
			$filename = $_ls[count($_ls) - 1];
			if($_ls[0] == 'MAIJI'){
				$filename = explode('\\',$class);
				$filename = $filename[count($filename) - 1];
				array_pop($_ls);
				array_shift($_ls);
				$path = implode('/',$_ls);
				$cflag = Loader::searchFile($filename,APP_INI_PATH.'libs/'.$path.'/');
				$mfalg = Loader::searchFile($filename,APP_INI_PATH.'libs/'.$path.'/');
			}elseif($_ls[0] == 'APP'){
				if(!is_dir(APP_PATH.$_ls[1])){
					die(\MAIJI\APP_Error::display('项目目录不存在',APP_PATH.$_ls[1]));
				}
				$cflag = Loader::searchFile($filename,APP_PATH . $_ls[1] . '/controller/');
				$mfalg = Loader::searchFile($filename,APP_PATH . $_ls[1] . '/model/');
			}else{
				$cflag = Loader::searchFile($filename,APP_PATH . $_ls[1] . '/controller/');
				$mfalg = Loader::searchFile($filename,APP_PATH . $_ls[1] . '/model/');
			}
			$path = false;
			$path = ($cflag != false)? $cflag:$path;
			$path = ($mfalg != false)? $mfalg:$path;
			if($path == false){
				die(\MAIJI\APP_Error::display('找不到这个文件：'.$filename,APP_PATH.$_ls[1]));
			}else{
				require_once($path);
			}
		}else{
			$filename = strtolower($class).".php";
			$cflag = Loader::searchFile($filename,APP_INI_PATH.'smarty/');
			$path = false;
			$path = ($cflag != false)? $cflag:$path;
			if($path !== false){
				require_once($path);
			}
		}
    }
}
Loader::baseLoad();
spl_autoload_register(array('Loader', 'autoload'));
